import pygame
import sys
import random

SCREEN_X = 500
SCREEN_Y = 520

# 显示文字
def show_text(screen, pos, text, color, font_bold=False, font_size=40, font_italic=False):
    cur_font = pygame.font.SysFont("SimHei", font_size)
    cur_font.set_bold(font_bold)
    cur_font.set_italic(font_italic)
    text_fmt = cur_font.render(text, 1, color)
    screen.blit(text_fmt, pos)

# 蛇
class Snake(object):

    def __init__(self):
        # 默认方向右
        self.dirction = pygame.K_RIGHT
        # 蛇身
        self.body = []
        # 给蛇身添加5个节点
        for x in range(5):
            self.addnode()

    # 添加节点
    def addnode(self):
        left, top = (10, 10)
        if self.body:
            left, top = (self.body[0].left, self.body[0].top)
        node = pygame.Rect(left, top, 20, 20)
        if self.dirction == pygame.K_LEFT:
            node.left -= 20
        if self.dirction == pygame.K_RIGHT:
            node.left += 20
        if self.dirction == pygame.K_UP:
            node.top -= 20
        if self.dirction == pygame.K_DOWN:
            node.top += 20
        self.body.insert(0, node)

    # 删除最后一个节点
    def delnode(self):
        self.body.pop()

    # 改变方向
    def changedirection(self, curkey):
        LR = [pygame.K_LEFT, pygame.K_RIGHT]
        UD = [pygame.K_UP, pygame.K_DOWN]
        if curkey in LR + UD:
            if (curkey in LR) and (self.dirction in LR):
                return
            if (curkey in UD) and (self.dirction in UD):
                return
            self.dirction = curkey

    # 结束
    def isdead(self):
        if self.body[0].left >= 490 or self.body[0].left < 10:
            return True
        if self.body[0].top >= 470 or self.body[0].top < 10:
            return True
        if self.body[0] in self.body[1:]:
            return True
        return False

# 食物
class Food:
    def __init__(self):
        self.rect = pygame.Rect(0, 0, 20, 20)
        self.color = (0, 0, 0)
        self.set([])

    # 设置食物坐标和颜色
    def set(self, lists):
        self.rect.left = random.randrange(20, 460, 20) + 10
        self.rect.top = random.randrange(20, 440, 20) + 10
        self.color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))

        # 检测食物坐标是否与蛇身重叠
        if self.rect in lists:
            self.set(lists)

def main():
    pygame.init()
    screen_size = (SCREEN_X, SCREEN_Y)
    screen = pygame.display.set_mode(screen_size)
    pygame.display.set_caption('Snake')
    clock = pygame.time.Clock()
    scores = 0
    speed = 8
    isdead = False
    pause = False

    snake = Snake()
    food = Food()

    while True:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                # 退出程序
                sys.exit()
            if event.type == pygame.KEYDOWN:
                # 改变方向
                snake.changedirection(event.key)
                if event.key == pygame.K_SPACE:
                    if isdead:
                        # 游戏结束
                        return main()
                    else:
                        # 游戏暂停/开始
                        pause = not pause

        # 画界面
        screen.fill((228, 219, 219))
        pygame.draw.rect(screen, (255, 255, 255), [10, 10, 480, 460])

        # 检测游戏是否结束
        isdead = snake.isdead()

        # 吃食物和前进的处理
        if not isdead and pause == False:
            snake.addnode()
            if snake.body[0] == food.rect:
                scores += 1
                food.set(snake.body)
                speed = 8 + scores // 20
            else:
                snake.delnode()

        # 画食物
        pygame.draw.rect(screen, food.color, food.rect, 0)

        # 画蛇
        for rect in snake.body:
            pygame.draw.rect(screen, (85, 218, 95), rect, 0)

        # 游戏结束
        if isdead:
            show_text(screen, (50, 150), 'GAME OVER!', (234, 70, 70), False, 85)
            show_text(screen, (60, 250), '按空格键重新开始!', (234, 70, 70), False, 45)

        # 游戏暂停
        if pause:
            show_text(screen, (150, 150), '暂停!', (234, 70, 70), False, 85)
            show_text(screen, (60, 250), '按空格键重新开始!', (234, 70, 70), False, 45)

        # 显示分数
        show_text(screen, (10, 480), '分数: ' + str(scores), (106, 79, 247), False, 30)

        # 速度
        show_text(screen, (350, 480), '速度: ' + str(speed), (106, 79, 247), False, 30)

        # 界面渲染和延时
        pygame.display.update()
        clock.tick(speed)

if __name__ == '__main__':
    main()